package com.sdk.es.sdk.entity.common;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

import java.util.Objects;

import static com.sdk.es.sdk.entity.common.EsResultStatus.FAIL;
import static com.sdk.es.sdk.entity.common.EsResultStatus.SUCCESS;

@Setter
@Getter
@ToString
public class EsResult<T> {
    private Integer code;
    private String msg;
    private T data;

    private EsResult() {
    }

    public static <T> EsResult<T> success() {
        EsResult<T> result = new EsResult<>();
        result.setCode(SUCCESS.getCode());
        result.setMsg(SUCCESS.getReason());
        return result;
    }

    public static <T> EsResult<T> success(T data) {
        EsResult<T> result = new EsResult<>();
        result.setCode(SUCCESS.getCode());
        result.setMsg(SUCCESS.getReason());
        result.setData(data);
        return result;
    }

    public static <T> EsResult<T> fail(String msg) {
        EsResult<T> result = new EsResult<>();
        result.setCode(FAIL.getCode());
        result.setMsg(msg);
        result.setData(null);
        return result;
    }

    public static <T> EsResult<T> fail(T data) {
        EsResult<T> result = new EsResult<>();
        result.setCode(FAIL.getCode());
        result.setData(data);
        return result;
    }

    public static <T> EsResult<T> fail(Integer code, String msg) {
        EsResult<T> result = new EsResult<>();
        result.setCode(code);
        result.setMsg(msg);
        return result;
    }

    public static String failStr(String msg) {
        EsResult<?> result = new EsResult<>();
        result.setCode(FAIL.getCode());
        result.setMsg(msg);
        return JSONObject.toJSONString(result);
    }

    /**
     * 判断业务处理是否成功，不参与json序列化
     *
     * @return 业务处理是否成功
     */
    @JsonIgnore
    public boolean isOk() {
        return Objects.equals(SUCCESS.getCode(), code);
    }

}
